package com.un.ebs.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.product.domain.ProductClassAttr;
import com.un.ebs.product.domain.ProductClassAttrGroup;
import com.un.ebs.product.dto.ProductClassAttrGroupAddDto;
import com.un.ebs.product.dto.ProductClassAttrGroupUpdateDto;
import com.un.ebs.product.mapper.ProductClassAttrGroupMapper;
import com.un.ebs.product.mapper.ProductClassAttrMapper;
import com.un.ebs.product.service.ProductClassAttrGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liubo
 * @since 2019-11-03
 */
@Service
public class ProductClassAttrGroupServiceImpl extends ServiceImpl<ProductClassAttrGroupMapper, ProductClassAttrGroup> implements ProductClassAttrGroupService {

    @Autowired
    private ProductClassAttrMapper productClassAttrMapper;

    @Override
    public void add(ProductClassAttrGroupAddDto req) {
        ProductClassAttrGroup obj = new ProductClassAttrGroup();
        obj.setGroupName(req.getGroupName());
        obj.setClassId(req.getClassId());
        obj.setIsDelete(false);
        obj.setSort(getBaseMapper().maxSort());
        obj.insert();
    }

    @Override
    public void update(ProductClassAttrGroupUpdateDto req) {
        ProductClassAttrGroup obj = getById(req.getId());
        obj.setGroupName(req.getGroupName());
        obj.setClassId(req.getClassId());
        obj.updateById();
    }

    @Override
    public ProductClassAttrGroup queryById(String id) {
        return getBaseMapper().selectById(id);
    }

    @Override
    public void changeSort(String id, int index) {
        ProductClassAttrGroup obj = getById(id);
        obj.setSort(index);
        getBaseMapper().updateById(obj);
    }

    @Override
    public void delete(String id) {
        LambdaQueryWrapper<ProductClassAttr> lq = Wrappers.lambdaQuery();
        lq.eq(ProductClassAttr::getGroupId, id);
        lq.eq(ProductClassAttr::getIsDelete, false);
        if (productClassAttrMapper.selectCount(lq) > 0) {
            throw new BusinessException("属性分组下还包含了属性记录，请先删除属性记录。");
        }
        getBaseMapper().deleteById(id);
    }

}